﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CardGamesLibrary.Cards;
using CardGamesLibrary.Cards.Decks;
using CardGamesLibrary.Tables;

namespace CardGamesLibrary
{
    /// <summary>
    /// In games where cards are distributed among players, the "deal" is the act of that distribution.
    /// The dealer is the only one that keeps an instance of the deck during the game.
    /// </summary>
    public class Dealer<TCard> 
        where TCard : Card
    {
        private readonly GameTable<TCard> _table;
        private Deck<TCard> _deck;

        public Dealer(GameTable<TCard> table)
        {
            
            _table = table;
            _deck = table.CreateDeck();
        }

        private TCard Deal()
        {
            return _deck.GrabRandomCard();
        }
       
        private IEnumerable<TCard> Deal(int number)
        {
            for (var i = 0; i < number; i++)
            {
                yield return _deck.GrabRandomCard();
            }
        }

        public void DealTo(ICardSet<TCard> target)
        {
            var card = Deal();
            target.Add(card);
        }
        
        public void DealTo(IEnumerable<ICardSet<TCard>> targets, int number)
        {
            foreach (var target in targets)
            {
                DealTo(target,number);
            }
        }

        public void DealTo(ICardSet<TCard> target,int number)
        {
            var card = Deal(number);
            foreach (var c in card)
            {
                target.Add(c);
            }
        }


        public void DealTo(ICardPile<TCard> target)
        {
            var card = Deal();
            target.Add(card);
        }

        public void DealTo(ICardPile<TCard> target, int number)
        {
            var card = Deal(number);
            foreach (var c in card)
            {
                target.Add(c);
            }
        }

        public void DealTo(IEnumerable<ICardPile<TCard>> targets, int number)
        {
            foreach (var target in targets)
            {
                DealTo(target, number);
            }
        }

        public void RenewDeck()
        {
            _deck = _table.CreateDeck();
        }

    }
}
